<script setup lang="ts">
import { UserDto } from '@/app/api/api';
import { useApiStore } from '@/app/api/apiStore';
import foldIcon from '@/assets/ui/fold.svg'
import UserTypeDisplay from './UserTypeDisplay.vue';
import { useTreeMsgStore } from '../models/treeMsgStore';
import { onMounted } from 'vue';

interface UserDtoWithChildren extends UserDto{
    children?: UserDtoWithChildren[],
    expanded?: boolean
}
const props = defineProps<{
    user:UserDtoWithChildren
}>()
const api = useApiStore()
const treeMsgStore = useTreeMsgStore()

async function loadChildren() {
    props.user.children = await api.user.getChildren(props.user.id)??[]
    props.user.expanded = true
}
async function toggleExpand(){
    if(props.user.expanded){
        props.user.expanded = false
    }else{
        props.user.expanded = true
        if(!props.user.children){
            await loadChildren()
        }
    }
}
const emit = defineEmits<{
    (e:'startEdit', u:UserDto):void,
    (e:'startCreate', parent:UserDto):void,
}>()
onMounted(()=>{
    if(props.user.id){
        treeMsgStore.addCallback(props.user.id, ()=>{
            loadChildren()
        })
    }
})
</script>

<template>
<div class="utn">
    <div class="utnBody">
        <div>
            <img @click="toggleExpand" :src="foldIcon" class="expandBtn" :class="{expandBtnExpanded:user.expanded}"/>
            <div class="uinfo">
                <div class="uname">{{ user.name }}</div>
                <div class="uintro">{{ user.intro || '　' }}</div>
            </div>
        </div>
        <div style="margin-right: 8px;">
            <UserTypeDisplay :user-type="user.type"/>
            <button @click="emit('startCreate', user)" class="lite">添加</button>
            <button @click="emit('startEdit', user)" class="lite">编辑</button>
        </div>
    </div>
    <div class="utnChildren" v-if="user.expanded">
        <UserTreeNode v-for="i in user.children" :key="i.id" :user="i"
            @start-edit="u=>emit('startEdit', u)" @start-create="p=>emit('startCreate', p)"/>
    </div>
</div>
</template>

<style scoped lang="scss">
@use '../styles/userInfo.scss';

.utnBody{
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #eee;
    padding: 3px;
    &>div{
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 10px;
    }
    &:hover{
        background-color: #e0e0e0;
    }
}
.utnChildren{
    border-left: 3px solid #eee;
    padding: 5px 0px 5px 15px;
}
.expandBtn{
    width: 22px;
    height: 22px;
    object-fit: contain;
    object-position: center;
    margin-left: 4px;
    cursor: pointer;
    transform: rotate(-90deg);
    &.expandBtnExpanded{
        transform: rotate(0deg);
    }
}
</style>